package com.bw.sign

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.lib_base.entity.SignBeanItem
import com.bw.lib_base.mvvm.BaseActivity
import com.bw.sign.databinding.ActivitySignBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.Dispatcher
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Timer
import kotlin.concurrent.timerTask

@AndroidEntryPoint
@Route(path = "/sign/SignActivity")
class SignActivity : BaseActivity<ActivitySignBinding, SignViewModel>() {
    var timer: Timer? = null
    var date = SimpleDateFormat("dd")
    var sdf = SimpleDateFormat("HH:mm:ss")
    val spUtils = SPUtils.getInstance()
    override fun initView() {
        /*
        var today = date.format(System.currentTimeMillis())

        //        //先判断日期，如果当前日期大于打卡日期，则为新一天签到
        //        val rq = SPUtils.getInstance().getLong("rq")
        //        if (rq < today.toInt().toLong()){
        //            SPUtils.getInstance().remove("dk")
        //            SPUtils.getInstance().remove("late")
        //            SPUtils.getInstance().remove("time")
        //        }

        val dk = SPUtils.getInstance().getString("dk")
        val rq = SPUtils.getInstance().getLong("rq")
        val late = SPUtils.getInstance().getBoolean("late")
        val time = SPUtils.getInstance().getString("dkTime")
        if (date.format(System.currentTimeMillis()).toInt().toLong() - rq >= 1) {
            SPUtils.getInstance().remove("dk")
            SPUtils.getInstance().remove("late")
            SPUtils.getInstance().remove("time")
            binding.signTvdaka.setText("上午打卡")
            binding.btnSign.isEnabled = true
        }
        if (dk.isNullOrEmpty() && rq < today.toInt()) {
            binding.signTvdaka.setText("上午打卡")
        } else if (dk.equals("morning") && rq == today.toInt().toLong()) {
            binding.signTvdaka.setText("下午打卡")
            if (late) {
                binding.signTvtime.setText("${time}(迟到打卡)")
            } else {
                binding.signTvtime.setText("${time}(打卡成功)")
            }
        } else if (dk.equals("afternoon")) {
            binding.signTvdaka.setText("打卡结束")
            if (late) {
                binding.signTvtime.setText("${time}(迟到打卡)")
            } else {
                binding.signTvtime.setText("${time}(打卡成功)")
            }
            binding.btnSign.isEnabled = false
            binding.btnSign.setBackgroundResource(R.drawable.shape_solid_gray)
        }
//
//        fun latedk():String {
//        val dktime = System.currentTimeMillis()
//        SPUtils.getInstance().put("dktime",dktime)
//        val format = sdf.format(dktime)
//        if (dktime - (9*3600*1000) > 0 && dktime - 12*3600*1000 < 0 ){
//        return "${format}(迟到打卡)"
//        }else if (dktime - 12 * 3600 * 1000 > 0 && dktime - 18 * 3600 * 1000 < 0){
//        return "${format}(早退打卡)"
//        }else
//        return "${format}打卡成功"
//        }

//        fun daka(){
//        var flag = ""
//        if (flag.isNullOrEmpty()){//为空则表示今天还未签到
//        binding.signTvdaka.setText("下午打卡")
//        binding.signTvtime.setText("18:00-23:59")
//        SPUtils.getInstance().put("dkFlag","morning")
//        //判断迟到或早退
//        latedk()
//        }else{
//
//        }

//        }
        binding.btnSign.setOnClickListener {
            val dk = SPUtils.getInstance().getString("dk")
            val rq = SPUtils.getInstance().getLong("rq")
            if (dk.isNullOrEmpty() && rq < today.toInt()) {
                SPUtils.getInstance().put("dk", "morning")
                SPUtils.getInstance()
                    .put("rq", date.format(System.currentTimeMillis()).toInt().toLong())
                val time1 = System.currentTimeMillis()
                SPUtils.getInstance().put("dkTime", viewModel.getTime(time1))
                binding.signTvdaka.setText("下午打卡")
                binding.signTvtime.setText("18:00-23:59")
                val time = SPUtils.getInstance().getString("dkTime")
                if (time1 - (9 * 60 * 60 * 1000) > 0) {
                    binding.signTvtime.setText("${time}(迟到打卡)")
                    SPUtils.getInstance().put("late", true)
                } else {
                    binding.signTvtime.setText("${time}(打卡成功)")
                    SPUtils.getInstance().put("late", false)
                }
            } else if (dk.isNotEmpty() && rq == today.toInt().toLong()) {
                binding.signTvdaka.setText("打卡结束")
                SPUtils.getInstance().put("dk", "afternoon")
                val time1 = System.currentTimeMillis()
                SPUtils.getInstance().put("dkTime", viewModel.getTime(time1))
                val time = SPUtils.getInstance().getString("dkTime")
                if (time1 - (18 * 60 * 60 * 1000) > 0) {
                    binding.signTvtime.setText("${time}(早退打卡)")
                    SPUtils.getInstance().put("late", true)
                } else {
                    binding.signTvtime.setText("${time}(打卡成功)")
                    SPUtils.getInstance().put("late", false)
                }
                binding.btnSign.isEnabled = false
                binding.btnSign.setBackgroundResource(R.drawable.shape_solid_gray)
            }

        }
*/


        binding.conLocation.setOnClickListener {
            ARouter.getInstance().build("/sign/MapActivity").navigation()
        }

        lifecycleScope.launch(Dispatchers.IO) {
            timer = Timer()
            timer?.schedule(timerTask {
                val time = viewModel.getTime(System.currentTimeMillis())

                lifecycleScope.launch(Dispatchers.Main) {
                    binding.signTime.setText("${time}")
                }
            }, 0, 1000)
        }
        val dateFont = viewModel.getDateFont(System.currentTimeMillis())
        val s = TimeUtils.getChineseWeek(System.currentTimeMillis()).replace("周", "星期")

        val week = viewModel.getWeek(System.currentTimeMillis())
        binding.signDate.setText("${week}")

        // 存储格式 sign/sout, 2025-06-07

        val info = spUtils.getString("dk", "")
        if (info.isNotEmpty()){
            val split = info.split(",")
            if (split[1] != viewModel.getDateFont(System.currentTimeMillis())){//今天打过卡
                if (split[0] == "sign"){//今天打了上班卡
                    binding.signTvdaka.setText("下班打卡")
                    binding.signTvtime.setText("18:00-24:00")
                }else{//说明今天打了下班卡
                    binding.btnSign.isEnabled = false
                    binding.btnSign.setBackgroundResource(R.drawable.shape_solid_gray)
                }
            }
        }

        binding.btnSign.setOnClickListener {
            val mills = System.currentTimeMillis()
            var status = "正常"
            var morning = ""
            var afternoon = ""
            if (binding.signTvdaka.text.toString() == "上午打卡"){
                morning = viewModel.getDate(mills)
                if (morning.split(" ")[1] > "09:00:00"){
                    status = "迟到"
                }
            }else{
                afternoon = viewModel.getDate(mills)
                if (afternoon.split(" ")[1] < "18:00:00"){
                    status = "早退"
                }
            }
            val signBeanItem = SignBeanItem(
                afternoon,
                spUtils.getString("lat", ""),
                null,
                "八维学院",
                morning,
                status,
                spUtils.getInt("uid")
            )
            viewModel.sign(signBeanItem)
        }

        binding.histroy.setOnClickListener {
            ARouter.getInstance().build("/sign/SignHistoryActivity").navigation()
        }
    }

    override fun initData() {
        viewModel.signData.observe(this){
//            ToastUtils.showLong("打卡成功")
            if (it.morningCheckIn.isNullOrEmpty()){
                spUtils.put("dk","sout,${viewModel.getDate(System.currentTimeMillis())}")
                binding.btnSign.isEnabled = false
                binding.btnSign.setBackgroundResource(R.drawable.shape_solid_gray)
            }else{
                spUtils.put("dk","sign,${viewModel.getDate(System.currentTimeMillis())}")
                binding.signTvdaka.setText("下午打卡")
                binding.signTvtime.setText("18:00-24:00")
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (timer != null) {
            timer?.cancel()
            timer == null
        }
    }
}